package com.dhy.qigsaw.splash.data

import android.annotation.SuppressLint
import android.content.Context
import com.dhy.qigsaw.splash.ApiUtil
import com.dhy.qigsaw.splash.splitInfoMd5
import com.dhy.qigsaw.splash.updateQigsawSplits
import com.dhy.xpreference.XPreferences
import com.qigsaw.share.SplitsVersion
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import org.greenrobot.eventbus.EventBus

class SplitInfoUpdateUtil(private val context: Context) {
    private val setting: SplitInfoMd5 = XPreferences.get(context)
    private lateinit var splitInfoMd5: String
    private var version: Long = 0
    fun isNew(url: String?): Boolean {
        splitInfoMd5 = url?.splitInfoMd5() ?: return false
        version = SplitsVersion.parse(url.replace(".apk", ".json"))?.date ?: 0
        return setting.splitInfoMd5 != splitInfoMd5 && version > setting.version
    }

    fun save(notifyUpdated: Boolean, isForceUpdate: Boolean = false) {
        setting.splitInfoMd5 = splitInfoMd5
        setting.version = version
        XPreferences.put(context, setting)

        if (notifyUpdated) {
            val msg = SplitInfoUpdated()
            msg.isForceUpdate = isForceUpdate
            EventBus.getDefault().postSticky(msg)
        }
    }

    fun updateSetting(splitInfoMd5: String, version: Long) {
        this.splitInfoMd5 = splitInfoMd5
        this.version = version
        save(false)
    }

    @SuppressLint("CheckResult")
    fun updateQigsawSplits(url: String, done: (compat: Boolean?) -> Unit) {
        ApiUtil.api.download(url)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                val updated = context.updateQigsawSplits(it)
                done(updated)
            }, {
                done(null)
                it.printStackTrace()
            })
    }
}